package gobase

import (
	"strconv"
	"strings"
)

func StrToIntDef(s string, defval int) int {
	v, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		return defval
	} else {
		return int(v)
	}
}

func StrToFloat32Def(s string, defval float32) float32 {
	v, err := strconv.ParseFloat(s, 32)
	if err != nil {
		return defval
	} else {
		return float32(v)
	}
}

func StrToFloat64Def(s string, defval float64) float64 {
	v, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return defval
	} else {
		return float64(v)
	}
}

func StrToInt64Def(s string, defval int64) int64 {
	v, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		if strings.HasPrefix(s, "0x") {
			v, err := strconv.ParseInt(s[2:], 16, 64)
			if err != nil {
				return defval
			} else {
				return v
			}
		}
		return defval
	} else {
		return int64(v)
	}
}

func StrToInt8Def(s string, defval int8) int8 {
	return int8(StrToInt64Def(s, int64(defval)))
}

func StrToUint64Def(s string, defval uint64) uint64 {
	v, err := strconv.ParseUint(s, 10, 64)
	if err != nil {
		if strings.HasPrefix(s, "0x") {
			v, err := strconv.ParseUint(s[2:], 16, 64)
			if err != nil {
				return defval
			} else {
				return v
			}
		}
		return defval
	} else {
		return v
	}
}

func TryStrToBool(str string, def bool) bool {
	if len(str) == 0 {
		return def
	}

	return str == "true" || str == "TRUE" || str == "1" || str == "YES" || str == "yes" || str == "是"
}
